package admin

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type ActivityController struct{}

// Index 活动列表
func (ctrl *ActivityController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	keyword := c.Query("keyword")
	category := c.Query("category")

	var activities []models.Activity
	var total int64

	db := config.DB.Model(&models.Activity{})

	if keyword != "" {
		db = db.Where("title LIKE ?", "%"+keyword+"%")
	}
	if category != "" {
		db = db.Where("category = ?", category)
	}

	db.Count(&total)
	db.Order("sort desc, id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&activities)

	utils.Success(c, models.PageResponse{
		List:     activities,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Add 添加活动
func (ctrl *ActivityController) Add(c *gin.Context) {
	var activity models.Activity
	if err := c.ShouldBindJSON(&activity); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Create(&activity).Error; err != nil {
		utils.Error(c, "添加失败")
		return
	}

	utils.Success(c, activity, "添加成功")
}

// Edit 编辑活动
func (ctrl *ActivityController) Edit(c *gin.Context) {
	var req struct {
		ID uint `json:"id" binding:"required"`
		models.Activity
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	var activity models.Activity
	if err := config.DB.First(&activity, req.ID).Error; err != nil {
		utils.Error(c, "活动不存在")
		return
	}

	req.Activity.ID = req.ID
	if err := config.DB.Save(&req.Activity).Error; err != nil {
		utils.Error(c, "更新失败")
		return
	}

	utils.Success(c, req.Activity, "更新成功")
}

// Delete 删除活动
func (ctrl *ActivityController) Delete(c *gin.Context) {
	var req struct {
		ID uint `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Delete(&models.Activity{}, req.ID).Error; err != nil {
		utils.Error(c, "删除失败")
		return
	}

	utils.Success(c, nil, "删除成功")
}
